package cn.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.struts2.json.annotations.JSON;

import cn.biz.GoodsBiz;
import cn.biz.OrdersBiz;
import cn.biz.UserBiz;
import cn.entity.Goods;
import cn.entity.Orders;
import cn.entity.User;
import cn.util.CreatLastWeek;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

public class UserAction implements Action {
	private UserBiz userBiz;
	private OrdersBiz ordersBiz;
	private GoodsBiz goodsBiz;
	private User user;
	private String checkpassword;
	private String resultStr = "";
	private String errorMessage = "";

	public Map<String, Object> getSession() {
		return ActionContext.getContext().getSession();
	}
	
	public User getSessionUser() {
		return (User) getSession().get("loginUser");
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	@JSON(serialize = false)
	public String getResultStr() {
		return resultStr;
	}

	public void setResultStr(String resultStr) {
		this.resultStr = resultStr;
	}

	public UserBiz getUserBiz() {
		return userBiz;
	}

	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}

	public OrdersBiz getOrdersBiz() {
		return ordersBiz;
	}

	public void setOrdersBiz(OrdersBiz ordersBiz) {
		this.ordersBiz = ordersBiz;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getCheckpassword() {
		return checkpassword;
	}

	public void setCheckpassword(String checkpassword) {
		this.checkpassword = checkpassword;
	}

	public GoodsBiz getGoodsBiz() {
		return goodsBiz;
	}

	public void setGoodsBiz(GoodsBiz goodsBiz) {
		this.goodsBiz = goodsBiz;
	}

	// 用户登陆
	public String login() {
		Map<String, Object> session = getSession();
		String result = ERROR;
		List<User> userList = userBiz.login(user);
		if (userList.size() > 0) {
			if(1 != userList.get(0).getIsDelete().intValue()) {
				System.out.println("当前登陆用户为："+userList.get(0).getName());
				// System.out.println(result);
				session.put("loginUser", userList.get(0));
				result = SUCCESS;
			} else {
				result = "ban";
			}
		}
		return result;
	}

	// 管理员登陆
	public String adminlogin() {
		Map<String, Object> session = getSession();
		String result = ERROR;
		List<User> userList = userBiz.login(user);
		if (userList.size() > 0) {// 用户类型要为管理员类型
			User user = userList.get(0);
			if (user.getType().equals("1")) {
				result = SUCCESS;
				System.out.println("管理员"+user.getName()+"登陆");
				session.put("loginUser", user);
			} else {
				result = ERROR;
				errorMessage = "您不是管理员";
				session.put("errorMsg", errorMessage);
			}
		} else {
			result = ERROR;
			errorMessage = "用户名或密码错误";
			session.put("errorMsg", errorMessage);
		}
		return result;
	}

	// 用户登出
	public String logout() {
		Map<String, Object> session = getSession();
		session.remove("loginUser");
		return SUCCESS;
	}

	// 用户初步注册
	public String regist() {
		if (user.getPassword().equals(checkpassword)) {
			user.setType("2");
			user.setIsDelete(0);
			return userBiz.insert(user);
		} else {
			return ERROR;
		}
	}
	
	//检查用户名是否被占用
	public String usernameCheck(){
		if(userBiz.isExist(user)){
			resultStr = "{\"flag\":\"error\"}";
		} else {
			resultStr = "{\"flag\":\"success\"}";
		}
		return SUCCESS;
	}

	//个人中心显示当前用户信息
	public String UserView() {
		String result = SUCCESS;
		user = getSessionUser();
		if (user == null) {
			result = "nologin";
		}
		return result;
	}

	//个人中心编辑用户信息
	public String UserEdit() {
		user.setId(getSessionUser().getId());
		userBiz.update(user);
		Map<String, Object> session = getSession();
		session.put("loginUser", user);
		return SUCCESS;
	}
	
	/*
	 * 用户管理 获取所有用户列表
	 */
	public String getUserList() {
		List<User> list = userBiz.getAllUsers();
		StringBuffer str = new StringBuffer("{result:[");
		if (list.size() > 0) {
			int j = 0;
			for (User u : list) {
				if (j > 0) {
					str.append(",");
				}
				str.append("{");
				str.append("id:").append(u.getId()).append(",");
				str.append("username:'").append(u.getUsername()).append("',");
				str.append("name:'")
				.append(u.getName() == null ? "" : u.getName())
				.append("',");
				str.append("address:'")
				.append(u.getAddress() == null ? "" : u.getAddress())
				.append("',");
				str.append("email:'")
				.append(u.getEmail() == null ? "" : u.getEmail())
				.append("',");
				str.append("phone:'")
				.append(u.getPhone() == null ? "" : u.getPhone())
				.append("',");
				str.append("sex:'").append(u.getSex() == null ? "" : u.getSex())
				.append("',");
				str.append("isDelete:'").append(u.getIsDelete() == null ? "" : u.getIsDelete())
				.append("'");
				str.append("}");
				j++;
			}
		}
		str.append("]}");
		resultStr = str.toString();
		return SUCCESS;
	}

	//后台首页和简单的统计功能
	public String backWelcome() {
		List<Orders> olist = ordersBiz.getAll();
		int completedOrders = 0, pendingOrders = 0;
		float completedMoney = 0;
		for (Orders orders : olist) {
			if ("004".equals(orders.getStatus())) {
				completedOrders += 1;
				completedMoney += orders.getMoney();
			} else if (!"999".equals(orders.getStatus())) {
				pendingOrders += 1;
			}
		}
		Map<String, Object> showMap = new HashMap<String, Object>();
		showMap.put("userSize", userBiz.getAllUsers().size());
		showMap.put("pendingOrders", pendingOrders);
		showMap.put("completedOrders", completedOrders);
		showMap.put("completedMoney", completedMoney);
		JSONObject json = JSONObject.fromObject(showMap);
		resultStr = json.toString();
		return SUCCESS;
	}
	
	//后台账号的封禁与解封
	public String setUserIsDelete() {
		Integer id = user.getId();
		Integer isDelete = user.getIsDelete();
		User user = userBiz.getUserById(id);
		user.setIsDelete(isDelete);
		try {
			userBiz.update(user);
			if(new Integer(1).equals(isDelete)) {
				List<Goods> list = goodsBiz.getGoodsBySeller(id);
				for (Goods goods : list) {
					goods.setIsDelete(1);
					goodsBiz.update(goods);
				}
			}
			resultStr = "{\"flag\":\"success\"}";
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = "{\"flag\":\"error\"}";
		}
		return SUCCESS;
	}
	
	//后台显示指定用户详情
	public String userManageView() {
		Integer id = user.getId();
		user = userBiz.getUserById(id);
		return SUCCESS;
	}
	
	//后台修改用户信息
	public String userManageEdit() {
		Integer id = user.getId();
		String name = user.getName();
		String password = user.getPassword();
		String email = user.getEmail();
		user = userBiz.getUserById(id);
		user.setName(name);
		user.setPassword(password);
		user.setEmail(email);
		try {
			if("1".equals(getSessionUser().getType())) {
				userBiz.update(user);
				resultStr = "{\"flag\":\"success\"}";
			} else {
				resultStr = "{\"flag\":\"errorUser\"}";
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = "{\"flag\":\"error\"}";
		}
		return SUCCESS;
	}
	
	public String welcomeLine() {
		String[] lastWeek= CreatLastWeek.getLastWeek("yyyy-MM-dd");
		List<Integer> dataList = new ArrayList<Integer>();
		dataList = ordersBiz.getLastWeekCompleteSize(lastWeek);
		List<String> dateList = new ArrayList<String>(Arrays.asList(lastWeek));
		dateList.remove(dateList.size()-1);
		/*String[] dateList = new String[7];
		for (int i = 0; i < dateList.length; i++) {
			dateList[i] = lastWeek[i];
		}*/
		JSONObject json = new JSONObject();
		json.put("dataList", dataList);
		json.put("dateList", dateList);
		resultStr = json.toString();
		return SUCCESS;
	}
	
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return SUCCESS;
	}
}
